package com.zhentao.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.injector.methods.SelectList;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.mapper.ChargeUserGoodsMapper;
import com.zhentao.mapper.ChargeUserHistorygiftMapper;
import com.zhentao.mapper.ChargeUserMapper;
import com.zhentao.model.common.dtos.ResponseResult;
import com.zhentao.model.common.enums.AppHttpCodeEnum;
import com.zhentao.model.pojo.user.ChargeUser;
import com.zhentao.model.pojo.user.gift.ChargeUserGift;
import com.zhentao.model.pojo.user.gift.ChargeUserHistorygift;
import com.zhentao.model.pojo.user.gift.vo.GiftVo;
import com.zhentao.model.pojo.user.goods.ChargeUserGoods;
import com.zhentao.service.ChargeAddBenefit;
import com.zhentao.service.ChargeUserGiftService;
import com.zhentao.mapper.ChargeUserGiftMapper;
import com.zhentao.user.ChargeUserThreadUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import static com.zhentao.model.common.enums.AppHttpCodeEnum.CHARGE_USER_CODE_ERROR;
import static com.zhentao.model.common.enums.AppHttpCodeEnum.PARAM_REQUIRE;

/**
 * @author Wl177
 * @description 针对表【charge_user_gift】的数据库操作Service实现
 * @createDate 2024-12-27 14:00:36
 */
@Service
public class ChargeUserGiftServiceImpl extends ServiceImpl<ChargeUserGiftMapper, ChargeUserGift>
        implements ChargeUserGiftService {

    @Resource
    private ChargeUserGiftMapper chargeUserGiftMapper;
    @Resource
    private ChargeUserHistorygiftMapper chargeUserHistorygiftMapper;
    @Resource
    private ChargeUserMapper chargeUserMapper;
    @Resource
    private ChargeUserGoodsMapper chargeUserGoodsMapper;
    @Autowired
    private ChargeAddBenefit addBenefit;

    @Override
    public ResponseResult getGifts() {
        List<ChargeUserGift> chargeUserGifts = chargeUserGiftMapper.selectList(null);
        return ResponseResult.okResult(chargeUserGifts);
    }

    @Override
    @Transactional
    public ResponseResult addGift(Integer id) {
        System.err.println(id + "----------------gift---id");
        //获取当前用户
        ChargeUser user = ChargeUserThreadUtils.getChargeUserThreadLocal();
        ChargeUser one = chargeUserMapper.selectOne(Wrappers.<ChargeUser>lambdaQuery().eq(ChargeUser::getId, user.getId()));
        //检查参数
        if (id == null) {
            return ResponseResult.errorResult(PARAM_REQUIRE);
        }
        ChargeUserHistorygift chargeUserHistorygift = new ChargeUserHistorygift();
        chargeUserHistorygift.setUserId(one.getId().intValue());
        chargeUserHistorygift.setGiftId(id);
        chargeUserHistorygift.setCreateTime(new Date());
        chargeUserHistorygiftMapper.insert(chargeUserHistorygift);
        one.setPoint(one.getPoint() - 100);
        chargeUserMapper.updateById(one);
        return ResponseResult.okResult("添加成功");
    }

    @Override
    public ResponseResult getUserHistoryGift() {
        //获取当前登录用户
        ChargeUser user = ChargeUserThreadUtils.getChargeUserThreadLocal();
        List<ChargeUserHistorygift> chargeUserHistorygifts = chargeUserHistorygiftMapper
                .selectList(Wrappers.<ChargeUserHistorygift>lambdaQuery()
                        .eq(ChargeUserHistorygift::getUserId, user.getId())
                        .orderByDesc(ChargeUserHistorygift::getCreateTime));
        List<GiftVo> giftVos = new ArrayList<>();
        if (chargeUserHistorygifts != null && chargeUserHistorygifts.size() > 0) {
            for (ChargeUserHistorygift chargeUserHistorygift : chargeUserHistorygifts) {
                GiftVo giftVo = new GiftVo();
                BeanUtil.copyProperties(chargeUserHistorygift, giftVo);
                ChargeUserGift chargeUserGift = chargeUserGiftMapper.
                        selectOne(Wrappers.<ChargeUserGift>lambdaQuery().eq(ChargeUserGift::getId, chargeUserHistorygift.getGiftId()));
                giftVo.setChargeUserGift(chargeUserGift);
                giftVos.add(giftVo);
            }
        }
        return ResponseResult.okResult(giftVos);
    }


    @Override
    @Transactional
    public ResponseResult exchangeGoods(Integer giftId) {
        //获取用户对象
        ChargeUser user = ChargeUserThreadUtils.getChargeUserThreadLocal();
//        System.out.println(user);
        //根据礼物id查询礼物对象
        ChargeUserHistorygift chargeUserHistorygiftlist = chargeUserHistorygiftMapper.selectOne(Wrappers.<ChargeUserHistorygift>lambdaQuery()
                .eq(ChargeUserHistorygift::getId, giftId)
                .eq(ChargeUserHistorygift::getUserId, user.getId())
                .orderByDesc(ChargeUserHistorygift::getCreateTime));
        if (chargeUserHistorygiftlist == null) {
            return ResponseResult.okResult(PARAM_REQUIRE);
        }
        // 查询出来兑换对应的商品，扣减用户积分，并且将兑换的商品状态进行一个改变
        // 查询当前用户的可用积分
        ChargeUser chargeUser = chargeUserMapper.selectOne(Wrappers.<ChargeUser>lambdaQuery()
                .eq(ChargeUser::getId, user.getId()));
        if (!StringUtils.isEmpty(chargeUser)) {
            // 根据查询到的礼物，获取对应商品的积分
            Integer chargeUserHistorygiftlistGiftId = chargeUserHistorygiftlist.getGiftId();
            ChargeUserGift chargeUserGift = chargeUserGiftMapper.selectOne(Wrappers.<ChargeUserGift>lambdaQuery()
                    .eq(ChargeUserGift::getId, chargeUserHistorygiftlistGiftId));
            // 判断抽中的是否为 20积分 如果是的话不需要扣减等操作，直接添加到对应的账户中
            if (chargeUserGift == null) return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR);
            if (chargeUserGift.getDescription().equals("安慰奖")) {
                chargeUser.setPoint(chargeUser.getPoint() + 20);
                chargeUserMapper.updateById(chargeUser);
                // 添加兑换记录
                updateHistoryGift(chargeUserHistorygiftlist);
            } else {
                if (chargeUser.getPoint() >= chargeUserGift.getPoint()) {
                    // 积分够
                    // 扣减积分
                    chargeUser.setPoint(chargeUser.getPoint() - chargeUserGift.getPoint());
                    chargeUserMapper.updateById(chargeUser);
                    updateHistoryGift(chargeUserHistorygiftlist);
                } else {
                    return ResponseResult.errorResult(450000, "积分不足，暂时不能兑换该商品");
                }
            }
        }
        // 兑换完成添加到对应的用户商品中
        ChargeUserGoods chargeUserGoods = new ChargeUserGoods();
        chargeUserGoods.setUserId(user.getId().intValue());
        chargeUserGoods.setGiftId(chargeUserHistorygiftlist.getGiftId());
        chargeUserGoods.setCreateTime(new Date());
        chargeUserGoodsMapper.insert(chargeUserGoods);
        ResponseResult result = ResponseResult.okResult("兑换成功");
        // 异步添加 积分变化史
        addBenefit.purchaseShop(chargeUserGoods);

        return result;
    }



    @Override
    public ResponseResult saveGift(ChargeUserGift gift) {
        List<ChargeUserGift> chargeUserGifts = chargeUserGiftMapper.selectList(null);
        if (chargeUserGifts.size() == 8) {
            return ResponseResult.errorResult(CHARGE_USER_CODE_ERROR);
        }
        ChargeUserGift chargeUserGift = chargeUserGiftMapper.selectOne(Wrappers.<ChargeUserGift>lambdaQuery().eq(ChargeUserGift::getId, gift.getId()));
        if (chargeUserGift != null) {
            return ResponseResult.errorResult(CHARGE_USER_CODE_ERROR);
        }

        chargeUserGiftMapper.insert(gift);
        return ResponseResult.okResult("添加成功");
    }

    @Override
    public ResponseResult updateGift(ChargeUserGift gift) {
        //检查参数
        if (gift == null) {
            return ResponseResult.errorResult(PARAM_REQUIRE);
        }
        //判断参数是否存在
        ChargeUserGift chargeUserGift = chargeUserGiftMapper.selectOne(Wrappers.<ChargeUserGift>lambdaQuery().eq(ChargeUserGift::getId, gift.getId()));
        if (chargeUserGift == null) {
            return ResponseResult.errorResult(CHARGE_USER_CODE_ERROR);
        }
        int i = chargeUserGiftMapper.updateById(gift);
        return ResponseResult.okResult("修改成功");
    }

    @Override
    public ResponseResult deleteGift(Integer id) {
        //检查参数
        if (id == null) {
            return ResponseResult.errorResult(PARAM_REQUIRE);
        }
        //判断参数是否存在
        ChargeUserGift chargeUserGift = chargeUserGiftMapper.selectOne(Wrappers.<ChargeUserGift>lambdaQuery().eq(ChargeUserGift::getId, id));
        if (chargeUserGift == null) {
            return ResponseResult.errorResult(CHARGE_USER_CODE_ERROR);
        }
        int i = chargeUserGiftMapper.deleteById(id);
        return ResponseResult.okResult("删除成功");

    }
    /**
     * @description 修改兑换奖品状态
     * @author 振涛教育_小Q
     * @date 2025/1/5 1:01
     * @param chargeUserHistorygiftlist
     * @return void
     */

    private void updateHistoryGift(ChargeUserHistorygift chargeUserHistorygiftlist) {
        chargeUserHistorygiftlist.setStatus(1);
        chargeUserHistorygiftlist.setCreateTime(new Date());
        chargeUserHistorygiftMapper.updateById(chargeUserHistorygiftlist);
    }
}




